<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>03.edit案例.html</title>
</head>
<style>
    span {
        border-bottom: 1px solid black;
        width: 100px;
        display: inline-block;
        text-align: center;
    }

    input {
        outline: 0;
        border: 0;
        border-bottom: 1px solid black;
        width: 100px;
        font-size: 16px;
        text-align: center;
    }
</style>

<body>
    <div id="app">
        <fieldset>
            <legend>03.edit案例.html</legend>
            <p v-for="(v,k,i) in userInfo">
                <label>{{k}}</label>
                :
                <input ref="ipt" type="text" @blur="blur(k)" v-model="val" v-if="isEdit&&selectedIndex===i">
                <span v-else @dblclick="edit(i,v)">{{v}}</span>
            </p>
        </fieldset>
    </div>
</body>

</html>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
    const vm = new Vue({
        el: "#app",
        data: {
            userInfo: {
                "姓名": "马西梅",
                "年龄": 18,
                "爱好": "夏洛",
                "身高": "150cm"
            },
            val: "",
            isEdit: false,//控制是否进入了编辑状态
            selectedIndex: "" //点击了哪一个p标签中span
        },
        methods: {
            edit(i, v) {
                //需要让input获取焦点,获取焦点一般都要操作dom
                // setTimeout(() => {
                //     console.log(this.$refs.ipt)
                //     this.$refs.ipt[0].focus()
                // })
                this.isEdit = true;
                this.selectedIndex = i;
                this.$nextTick(function () {
                    // console.log(this.$refs.ipt)
                    this.$refs.ipt[0].focus()
                })
                this.val = v;
            },
            //由于退出再进入的时候,userInfo并没有改变,而是再次的将原本值传了进来,导致无法更改,所以我们需要在失去焦点的时候,把userInfo的值一并改了
            blur(key) {
                this.userInfo[key] = this.val;
            }
        }
    })
</script>